package org.soarsky.wealthchengdu.module.guide;

import java.util.List;

import org.soarsky.wealthchengdu.R;

import android.app.ProgressDialog;
import android.graphics.Color;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.SearchRecentSuggestions;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.LocationManagerProxy;
import com.amap.api.location.LocationProviderProxy;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMap.InfoWindowAdapter;
import com.amap.api.maps.AMap.OnMapClickListener;
import com.amap.api.maps.AMap.OnMarkerClickListener;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.SupportMapFragment;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.search.core.AMapException;
import com.amap.api.search.core.LatLonPoint;
import com.amap.api.search.poisearch.PoiItem;
import com.amap.api.search.poisearch.PoiPagedResult;
import com.amap.api.search.poisearch.PoiSearch;
import com.amap.api.search.poisearch.PoiSearch.SearchBound;
import com.amap.api.search.poisearch.PoiTypeDef;
import com.amap.api.search.route.Route;

public class MapActivity extends FragmentActivity implements LocationSource,
		AMapLocationListener, InfoWindowAdapter, OnMarkerClickListener,
		View.OnClickListener, OnMapClickListener {

	protected static final String CHENGDU = "028";// 成都区号
	protected static final int SEARCHRANGE = 1000;// 搜索范围
	private final int MARKTNUM = 100;// 每一个切面内标记显示的最大数量

	private LayoutInflater layoutInFlater;

	private AMap aMap;
	private OnLocationChangedListener mListener;
	private LocationManagerProxy mAMapLocationManager; // 定位管理
	private UiSettings uisetting;// 高德UI管理器
	private Location locationMe;// 自己的经纬度

	/* 周边设施 */
	private Button mapStayBtn;// 住宿
	private Button mapDietBtn;// 饮食
	private Button mapTrafficBtn;// 公交
	// private Button btn4;
	private boolean Typeb;
	private PoiPagedResult result;// 获取地图mark
	// private int cnt;//地图mark数量
	private String query;
	// 30.6497110116642,104.066224917725 索菲特万达
	// 30.6750701847006,104.004041925034 香格里拉

	private int mode = Route.BusDefault;
	private LatLonPoint startPoint = null;
	private LatLonPoint endPoint = null;
	private List<Route> routeResult;
	private LinearLayout routeNav;
	private ImageButton routePre, routeNext;
	private RouteOverlay routeOverlay;
	private Route route;
	private boolean isClickStart = false;
	private boolean isClickTarget = false;
	private Marker startMk, targetMk, mapMarker;
	private ProgressDialog progDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		Logd.d("this is map create ");
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_map);
		init();
	}

	/**
	 * 选择矢量地图和卫星地图事件的响应
	 */
	private void setLayer(String layerName) {
		if (layerName.equals("Normal")) {
			aMap.setMapType(AMap.MAP_TYPE_NORMAL);
		} else if (layerName.equals("Satellite")) {
			aMap.setMapType(AMap.MAP_TYPE_SATELLITE);
		}
	}

	/**
	 * 初始化AMap对象
	 */
	private void init() {
		Logd.d("this is map init ");
		routeNav = (LinearLayout) findViewById(R.id.LinearLayoutLayout_index_bottom);
		routePre = (ImageButton) findViewById(R.id.pre_index);
		routeNext = (ImageButton) findViewById(R.id.next_index);
		mapStayBtn = (Button) findViewById(R.id.mapstay);
		mapDietBtn = (Button) findViewById(R.id.mapdiet);
		mapTrafficBtn = (Button) findViewById(R.id.maptraffic);
		mapStayBtn.setTag(Constants.STAYBTN);
		mapDietBtn.setTag(Constants.DIETBTN);
		mapTrafficBtn.setTag(Constants.TRAFFICBTN);
		routePre.setTag(Constants.ROUTEPRE);
		routeNext.setTag(Constants.ROUTENAV);
		layoutInFlater = LayoutInflater.from(getApplicationContext());
		// btn4.setTag(4);
		Typeb = true;
		routeNext.setOnClickListener(this);
		routePre.setOnClickListener(this);
		mapStayBtn.setOnClickListener(this);
		mapDietBtn.setOnClickListener(this);
		mapTrafficBtn.setOnClickListener(this);
		// btn4.setOnClickListener(new View.OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		// setLayer(!Typeb);
		// }
		// });

		if (aMap == null) {
			aMap = ((SupportMapFragment) getSupportFragmentManager()
					.findFragmentById(R.id.map)).getMap();
			if (AMapUtil.checkReady(this, aMap)) {
				uisetting = aMap.getUiSettings(); // UI管理器
				uisetting.setMyLocationButtonEnabled(false);
				setUpMap();
			}
		}
	}

	private void setUpMap() {
		mAMapLocationManager = LocationManagerProxy
				.getInstance(MapActivity.this);
		aMap.setLocationSource(this);
		aMap.setMyLocationEnabled(true);
		aMap.setOnMarkerClickListener(this);
		aMap.setInfoWindowAdapter(this);
		aMap.setOnMapClickListener(this);// 对amap添加单击地图事件监听器
		
	}

	private void setLayer(boolean bType) {
		if (bType) {
			aMap.setMapType(AMap.MAP_TYPE_NORMAL);
		} else {
			aMap.setMapType(AMap.MAP_TYPE_SATELLITE);
		}
		Typeb = !Typeb;
	}

	private boolean LocationMeB() {
		if (locationMe == null) {
			ToastUtil.show(getApplicationContext(), "正在定位，请稍后");
			return false;
		}
		return true;
	}

	@Override
	public void onLocationChanged(Location location) {
		if (location != null) {
			locationMe = location;
		}
	}

	@Override
	public void onProviderDisabled(String arg0) {

	}

	@Override
	public void onProviderEnabled(String arg0) {

	}

	@Override
	public void onStatusChanged(String arg0, int arg1, Bundle arg2) {

	}

	/**
	 * 定位成功后回调函数
	 */
	@Override
	public void onLocationChanged(AMapLocation location) {
		// TODO Auto-generated method stub
		if (mListener != null) {
			if (location != null) {
				mListener.onLocationChanged(location);
				locationMe = location;
				LatLng ll = new LatLng(location.getLatitude(),
						location.getLongitude());
				startPoint = AMapUtil.convertToLatLonPoint(ll);
//				ToastUtil.show(getApplicationContext(),
//						"获取位置成功lat -> " + locationMe.getLatitude() + "   log->"
//								+ locationMe.getLongitude());
			}
		}
	}

	@Override
	public void activate(OnLocationChangedListener arg0) {
		// TODO Auto-generated method stub
		mListener = arg0;
		if (mAMapLocationManager == null) {
			mAMapLocationManager = LocationManagerProxy.getInstance(this);
		}
		// 网络定位
		mAMapLocationManager.requestLocationUpdates(
				LocationProviderProxy.AMapNetwork, 10, 25, this);
	}

	@Override
	public void deactivate() {
		// TODO Auto-generated method stub
		mListener = null;
		if (mAMapLocationManager != null) {
			mAMapLocationManager.removeUpdates(this);
			mAMapLocationManager.destory();
		}
		mAMapLocationManager = null;
	}

	@Override
	public boolean onMarkerClick(Marker marker) {
		// TODO Auto-generated method stub
		marker.showInfoWindow();
		endPoint = AMapUtil.convertToLatLonPoint(marker.getPosition());
		Logd.d("markerClick!");
		mapMarker = marker;
		return true;
	}

	@Override
	public View getInfoContents(Marker arg0) {
		return null;
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		enableMyLocation();
		super.onResume();

	}

	public boolean enableMyLocation() {
		boolean result = false;
		if (mAMapLocationManager
				.isProviderEnabled(LocationProviderProxy.AMapNetwork)) {
			mAMapLocationManager.requestLocationUpdates(
					LocationProviderProxy.AMapNetwork, 0, 0, this);
			result = true;
		}
		return result;
	}

	private ImageButton drivingButton;
	private ImageButton transitButton;
	private ImageButton walkButton;

	@Override
	public View getInfoWindow(Marker arg0) {
		View view = (View) layoutInFlater.inflate(R.layout.activity_map_marker,
				null);
		walkButton = (ImageButton) view.findViewById(R.id.mapwalk);
		transitButton = (ImageButton) view.findViewById(R.id.mapbus);
		drivingButton = (ImageButton) view.findViewById(R.id.mapcar);
		walkButton.setTag(Constants.MAPWALK);
		transitButton.setTag(Constants.MAPBUS);
		drivingButton.setTag(Constants.MAPCAR);
		walkButton.setOnClickListener(this);
		transitButton.setOnClickListener(this);
		drivingButton.setOnClickListener(this);
		drivingButton.setBackgroundResource(R.drawable.mode_driving_off);
		transitButton.setBackgroundResource(R.drawable.mode_transit_off);
		walkButton.setBackgroundResource(R.drawable.mode_walk_off);
		TextView textTitle = (TextView) view.findViewById(R.id.maptitle);
		TextView textSnippet = (TextView) view.findViewById(R.id.mapsnippet);
		textTitle.setText(arg0.getTitle());
		textSnippet.setText(arg0.getSnippet());
		return view;

	}

	protected void doSearchQuery(final String query) {
		SearchRecentSuggestions suggestions = new SearchRecentSuggestions(
				MapActivity.this, FindSurrounding.AUTHORITY,
				FindSurrounding.MODE);
		suggestions.saveRecentQuery(query, null);
		 showProgressDialog();// 显示进度框
		// Toast.makeText(getApplicationContext(),
		// "lat -> "+locationMe.getLatitude() +
		// "   log->"+locationMe.getLongitude(), 1000).show();
		new Thread(new Runnable() {
			public void run() {
				try {
					PoiSearch poiSearch = new PoiSearch(MapActivity.this,
							new PoiSearch.Query(query, PoiTypeDef.All, CHENGDU)); // 设置搜索字符串，"010为城市区号"
					poiSearch.setPageSize(MARKTNUM);// 设置搜索每次最多返回结果数
					poiSearch.setBound(new SearchBound(
							new LatLonPoint(locationMe.getLatitude(),
									locationMe.getLongitude()), SEARCHRANGE));// 设置搜索范围
					result = poiSearch.searchPOI();
					handler.sendMessage(Message.obtain(handler,
							Constants.POISEARCH));
				} catch (AMapException e) {
					handler.sendMessage(Message
							.obtain(handler, Constants.ERROR));
					e.printStackTrace();
				}
			}
		}).start();

	}
	/**
	 * 显示进度框
	 */
	private void showProgressDialog() {
		if (progDialog == null)
			progDialog = new ProgressDialog(this);
		progDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		progDialog.setIndeterminate(false);
		progDialog.setCancelable(true);
		progDialog.setMessage("正在搜索:\n" + query);
		progDialog.show();
	}
	private void showPoiItem(List<PoiItem> poiItems) {
		if (poiItems != null && poiItems.size() > 0) {
			if (aMap == null)
				return;
			aMap.clear();
			LatLngBounds bounds = getLatLngBounds(poiItems);
			aMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 5));
			addMarkers(poiItems);
		} else {
			ToastUtil.show(getApplicationContext(), "没有搜索到数据！");
		}
	}

	private LatLngBounds getLatLngBounds(List<PoiItem> poiItems) {
		LatLngBounds.Builder b = LatLngBounds.builder();
		for (int i = 0; i < poiItems.size(); i++) {
			b.include(new LatLng(poiItems.get(i).getPoint().getLatitude(),
					poiItems.get(i).getPoint().getLongitude()));
		}
		return b.build();
	}

	/**
	 * 一次性打印多个Marker出来
	 */
	private void addMarkers(List<PoiItem> poiItems) {
		for (int i = 0; i < poiItems.size(); i++) {
			MarkerOptions m = new MarkerOptions();
			aMap.addMarker(new MarkerOptions()
					.position(
							new LatLng(
									poiItems.get(i).getPoint().getLatitude(),
									poiItems.get(i).getPoint().getLongitude()))
					.title(poiItems.get(i).getTitle())
					.snippet(poiItems.get(i).getSnippet())
					.icon(BitmapDescriptorFactory.defaultMarker()));
		}
		if (aMap.getMyLocation() != null) {
			aMap.setMyLocationEnabled(true);
			aMap.addMarker(new MarkerOptions()
					.position(
							new LatLng(locationMe.getLatitude(), locationMe
									.getLongitude()))
					.title("我的位置")
					.snippet(null)
					.icon(BitmapDescriptorFactory
							.fromResource(R.drawable.icon_locr_light)));
		}
	}
	/**
	 * 隐藏进度框
	 */
	private void dissmissProgressDialog() {
		if (progDialog != null) {
			progDialog.dismiss();
		}
	}
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			if (msg.what == Constants.POISEARCH) {
				 dissmissProgressDialog();// 隐藏对话框

				if (result != null) {
					new Thread(new Runnable() {
						@Override
						public void run() {
							try {
								final List<PoiItem> poiItems = result
										.getPage(1);
								runOnUiThread(new Runnable() {
									@Override
									public void run() {
										showPoiItem(poiItems);// 每页显示10个poiitem
									}
								});

							} catch (AMapException e) {
								e.printStackTrace();

							}
						}
					}).start();
				}

			} else if (msg.what == Constants.ERROR) {
				ToastUtil.show(getApplicationContext(), "搜索失败,请检查网络连接！");
			}
		}
	};

	public void searchRouteResult(LatLonPoint startPoint, LatLonPoint endPoint) {
		progDialog = ProgressDialog.show(MapActivity.this, null, "正在获取线路",
				true, true);
		final Route.FromAndTo fromAndTo = new Route.FromAndTo(startPoint,
				endPoint);
		Thread t = new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					routeResult = Route.calculateRoute(MapActivity.this,
							fromAndTo, mode);
					if (progDialog.isShowing()) {
						if (routeResult != null || routeResult.size() > 0)
							routeHandler.sendMessage(Message
									.obtain(routeHandler,
											Constants.ROUTE_SEARCH_RESULT));
					}
				} catch (AMapException e) {
					Message msg = new Message();
					msg.what = Constants.ROUTE_SEARCH_ERROR;
					msg.obj = e.getErrorMessage();
					routeHandler.sendMessage(msg);
				}
			}
		});
		t.start();

	}

	private Handler routeHandler = new Handler() {
		public void handleMessage(Message msg) {
			if (msg.what == Constants.ROUTE_SEARCH_RESULT) {
				progDialog.dismiss();
				aMap.clear();
				if (routeResult != null && routeResult.size() > 0) {
					route = routeResult.get(0);
					if (route != null) {
						routeOverlay = new RouteOverlay(MapActivity.this, aMap,
								route);
						routeOverlay.removeFormMap();
						routeOverlay.addMarkerLine();
						routeNav.setVisibility(View.VISIBLE);
						routePre.setBackgroundResource(R.drawable.prev_disable);
						routeNext
								.setBackgroundResource(R.drawable.btn_route_next);
					}
				}
			} else if (msg.what == Constants.ROUTE_SEARCH_ERROR) {
				progDialog.dismiss();
				ToastUtil.show(getApplicationContext(), (String) msg.obj);
			}
		}
	};

	@Override
	public void onClick(View v) {
		int key = Integer.parseInt(v.getTag().toString());
		if (LocationMeB()) {
			switch (key) {
			case Constants.STAYBTN:
				aMap.clear();
				if(routeOverlay != null){
					routeOverlay.close();
					setUpMap();
				}
				routeNav.setVisibility(View.GONE);
				query = "住宿";
				doSearchQuery("住宿");
				mapStayBtn.setTextColor(Color.RED);
				mapDietBtn.setTextColor(Color.BLACK);
				mapTrafficBtn.setTextColor(Color.BLACK);
				break;
			case Constants.DIETBTN:
				aMap.clear();
				if(routeOverlay != null){
					routeOverlay.close();
					setUpMap();
				}
				routeNav.setVisibility(View.GONE);
				query = "饮食";
				doSearchQuery("饮食");
				mapStayBtn.setTextColor(Color.BLACK);
				mapDietBtn.setTextColor(Color.RED);
				mapTrafficBtn.setTextColor(Color.BLACK);
				break;
			case Constants.TRAFFICBTN:
				aMap.clear();
				if(routeOverlay != null){
					routeOverlay.close();
					setUpMap();
				}
				routeNav.setVisibility(View.GONE);
				query = "交通";
				doSearchQuery("交通");
				mapStayBtn.setTextColor(Color.BLACK);
				mapDietBtn.setTextColor(Color.BLACK);
				mapTrafficBtn.setTextColor(Color.RED);
				break;
			case Constants.MAPWALK:
				mode = Route.WalkDefault;
				drivingButton
						.setBackgroundResource(R.drawable.mode_driving_off);
				transitButton
						.setBackgroundResource(R.drawable.mode_transit_off);
				walkButton.setBackgroundResource(R.drawable.mode_walk_on);
				searchRouteResult(startPoint, endPoint);
				break;
			case Constants.MAPBUS:
				mode = Route.BusDefault;
				drivingButton
						.setBackgroundResource(R.drawable.mode_driving_off);
				transitButton.setBackgroundResource(R.drawable.mode_transit_on);
				walkButton.setBackgroundResource(R.drawable.mode_walk_off);
				searchRouteResult(startPoint, endPoint);
				break;
			case Constants.MAPCAR:
				mode = Route.DrivingDefault;
				drivingButton.setBackgroundResource(R.drawable.mode_driving_on);
				transitButton
						.setBackgroundResource(R.drawable.mode_transit_off);
				walkButton.setBackgroundResource(R.drawable.mode_walk_off);
				searchRouteResult(startPoint, endPoint);
				break;
			case Constants.ROUTEPRE:
				if (routeOverlay != null) {
					boolean enablePre = routeOverlay.showPrePopInfo();
					if (!enablePre) {
						routePre.setBackgroundResource(R.drawable.prev_disable);
						routeNext
								.setBackgroundResource(R.drawable.btn_route_next);
					} else {
						routePre.setBackgroundResource(R.drawable.btn_route_pre);
						routeNext
								.setBackgroundResource(R.drawable.btn_route_next);
					}
				}
				break;
			case Constants.ROUTENAV:
				if (routeOverlay != null) {
					boolean enableNext = routeOverlay.showNextPopInfo();
					if (!enableNext) {
						routePre.setBackgroundResource(R.drawable.btn_route_pre);
						routeNext
								.setBackgroundResource(R.drawable.next_disable);
					} else {
						routePre.setBackgroundResource(R.drawable.btn_route_pre);
						routeNext
								.setBackgroundResource(R.drawable.btn_route_next);
					}
				}
				break;
			default:
				break;
			}
		}
		// setLayer(!Typeb);

	}

	@Override
	public void onMapClick(LatLng arg0) {
		// TODO Auto-generated method stub
		if(mapMarker != null){
			mapMarker.hideInfoWindow();
			mapMarker = null;
		}
	}

}